from werkzeug.security import generate_password_hash,check_password_hash
from flask import Blueprint,request,jsonify
import database
import json
import re
import random
from utils.redisconn import r
from utils.comm import send_message
from views.jwt_token import myjwt
import  time

from conf.comm import sqlalchemy_context
from database import *
from datetime import *
import datetime
#蓝图初始化



bp_users = Blueprint('users',__name__)

#注册功能实现
@bp_users.route('/reg',methods=['POST','GET','PUT','DELETE'])
@sqlalchemy_context()
def reg():
    data = request.data
    if not data:
        data = request.form
    else:
        data = json.loads(request.data)
    mobile = data['mobile']
    if not re.match('^1[3-9]\d{9}$', mobile):
        return jsonify({"code":11111})
    try:
        if request.method == 'POST':
            u = User(username=data['username'],password=generate_password_hash(data['password']),mobile=data['mobile'])
            db.session.add(u)
            db.session.commit()
            return jsonify({"code":200})
    except:
        return jsonify({"code":10010})


@bp_users.route('/sendsms',methods=['POST'])
def sendsms():
    # 获取传递手机号
    data = request.data
    if data:
        data = json.loads(request.data)
    else:
        data = request.form
    mobile = data['mobile']
    if not re.match('^1[3-9]\d{9}$', mobile):
        return jsonify({"code":11110,'mes': '输入正确手机号'})
    # 用手机号去redis中取验证码，如果能取到返回，请30秒后发
    v = r.get_str(mobile)
    if v:
        return jsonify({"code": 20021, 'mes': '请1分钟后发'})
        # 生成验证码
    code = str(random.randint(100000, 999999))
    # 调用短信接口
    flag = send_message(mobile, code, 1)
    if flag:
        # 发送成功，存入redis
        r.set_str(mobile, code, 60)
        # 返回结果（验证码）
        return jsonify({'code': 200, 'smscode': code})
    else:
        return jsonify({'code': 20011, 'mes': '发送失败，请重试'})

@bp_users.route('/mlogin',methods=['POST'])
@sqlalchemy_context()
def mlogin():
    data = request.data
    if data:
        data = json.loads(request.data)
    else:
        data = request.form
    mobile = data['mobile']
    code = data['code']
    if not re.match('^1[3-9]\d{9}$', mobile):
        return jsonify({"code":10010,'mes':"手机号错误"})
    if not code:
        return jsonify({"code": 10012, 'mes': "验证码不能为空"})
    user = database.User.query.filter_by(mobile=mobile).first()
    if not user:
        u = database.User(username = data['mobile'],mobile =data['mobile'])
        db.session.add(u)
        db.session.commit()
        r.del_str(mobile)
        token1 = myjwt.encode_jwt({'id': u.id})
        return jsonify({"code":200,'token':token1,'username':u.username,'userid':u.id})
    if r.get_str(mobile) == str(code):
        token = myjwt.encode_jwt({'id':user.id})
        return jsonify({"code":200,'token':token,'username':user.username,'userid':user.id})
    else:
        return jsonify({"code": 10013, 'mes': "验证码错误"})



import time
@bp_users.route('/login',methods=['POST'])
def login():
    data = json.loads(request.data)
    username = data['username']
    password = data['password']

    user = database.User.query.filter_by(username=username).first()
    start = datetime.datetime.now()

    if user:
        if check_password_hash(user.password,password):
            token = myjwt.encode_jwt({'id':user.id})
            return jsonify({"code":200,'token':token,'userid':user.id,'username':user.username})
        else:
            asd = database.User_request.query.filter_by(username=username).first()
            if not asd:
                usq = database.User_request(username=username,count=1)
                db.session.add(usq)
                db.session.commit()
            else:
                if start.timestamp() / 3600 >= asd.losertime.timestamp() / 3600 + 24:
                    database.User_request.query.filter_by(username=username).update({'count': 0, 'losertime': start})
                    db.session.commit()

                if asd.count < 3:
                    database.User_request.query.filter_by(username=username).update({'count':asd.count+1})
                    db.session.commit()
                else:
                    return jsonify({"code": 12345, 'mes': '密码今天只能输入三次'})
            return jsonify({"code":10010,'mes':'密码错误'})
    return jsonify({"code":10010,'mes':'用户名不存在'})

import os
import uuid

@bp_users.route('/getuserinfo')
@sqlalchemy_context()
def getuserinfo():
    userid = request.args.get('userid')
    user = database.User.query.filter_by(id = userid).first()
    dict = {}
    dict['id'] = user.id
    dict['username'] = user.username
    dict['mobile'] = user.mobile
    dict['avater'] = user.avater
    return jsonify({"code":200,"dict":dict})

@bp_users.route('/upload',methods=['POST'])
def upload():
    #获取文件
    file = request.files['file']
    #上传到upload文件夹
    #解决文件名被覆盖的问题
    #1.文件重命名   文件名.后缀  1.jpg   asfasfsdf.jpg
    #获取文件后缀
    filetext = os.path.splitext(file.filename)[1]
    newfile = uuid.uuid4().hex+filetext
    #2.在upload下面建立一个文件夹，专业存，文件夹的名字为userid
    userid = request.form.get('userid')
    #根据userid创建文件夹
    #判断此用户文件夹是否存在，存在直接写文件，不存在创建
    path = './static/upload/'+str(userid)
    #不存在创建文件
    if not os.path.exists(path):
        os.mkdir(path)
    file.save(os.path.join(path,newfile))
    #跟新到数据库
    avater = request.
    User.query.filter_by(id=userid).update({'avater':avater})
    db.session.commit()
    return jsonify({"code":200,'filename':newfile})


